#include "http_connection.h"

#include <iostream>

uint64_t request_count()
{
    static uint64_t count = 0;
    return ++count;
}

//返回当前时间戳
std::time_t now()
{
    return std::time(nullptr);
}



void HttpConnection::start()
{
    read_request();
    check_deadline();
}

void HttpConnection::read_request()
{
    auto self = shared_from_this();
    boost::beast::http::async_read(_socket, _buffer, _request, 
        [self](boost::beast::error_code ec, std::size_t bytes_transferred){
            if(!ec)
            {
                self->process_request();
            }
    });
}

void HttpConnection::check_deadline()
{
    auto self = shared_from_this();
    _deadline.async_wait([self](boost::system::error_code e){
        if(!e)
        {
            std::cerr << "deadline expired, ip: --"  << std::endl;
            self->_socket.close();
        }
    });
}

void HttpConnection::process_request()
{
    _response.version(_request.version());
    _response.keep_alive(false);

    switch(_request.method())
    {
        case boost::beast::http::verb::get:
            _response.result(boost::beast::http::status::ok);
            _response.set(boost::beast::http::field::server, "LightningBest-Beast");

            break;
        case boost::beast::http::verb::post:
            break;
        default:
            _response.result(boost::beast::http::status::bad_request);
            boost::beast::ostream(_response.body()) << "invalid request method '" 
                << std::string(_request.method_string()) << "'";
            std::cerr << "invalid request method ip: " << _socket.remote_endpoint() << std::endl;
            break;
    }

}


void HttpConnection::create_response()
{

}